//
//  ComposeController.swift
//  sinaDemo
//
//  Created by mac on 15/12/22.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

let textViewH: CGFloat = 200
let navH: CGFloat = 64

class ComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 把背景颜色改为白色
        view.backgroundColor = UIColor.whiteColor()
        addChildViewController(pictureVC)
        
        // 设置navitem
        setUpNavItem()
        
        // 设置titleview
        setUpTitleView()
        
        // 添加textview
        setUpTextView()
//        view.addSubview(textV)
        
        // 设置textview的toolbar
        setUpToolbar()
        
        // 设置pictureVC
        setUpPictureVC()
        
        // 注册通知
        notificationCenter.addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    // MARK: 通知方法
    @objc private func keyboardWillChange(notify: NSNotification) {
        print(notify.userInfo)
        /*
        UIKeyboardAnimationDurationUserInfoKey
        UIKeyboardFrameEndUserInfoKey
        */
        // 键盘的实时frame
        let endRect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 键盘的动画时间
        let duration = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 动画曲线值,为了抵消动画时间,对视图动画的影响
        let curve = (notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        let offset: CGFloat = endRect.origin.y - screenBounds.height
        // 更新约束
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        
        // 强制刷新UI界面
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    // 初始化控件
    private func setUpPictureVC() {
        view.insertSubview(pictureVC.view, belowSubview: toolbar)
        
        // 设置约束
        pictureVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    private func setUpToolbar() {
        // 添加toolbar
        view.addSubview(toolbar)
        toolbar.delegater = self
        
        // 设置约束
        toolbar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
    }
    
    private func setUpTextView() {
        view.addSubview(myTextView)
        myTextView.becomeFirstResponder()
        
        // 设置约束
        myTextView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(250)
        }
        
        myTextView.addSubview(placeHolderLabel)
        
        // 设置约束
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myTextView.snp_top).offset(8)
            make.left.equalTo(myTextView.snp_left).offset(5)
        }
    }
    
    private func setUpNavItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        let rightItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "compose")
        rightItem.enabled = false
        navigationItem.rightBarButtonItem = rightItem
    }
    
    private func setUpTitleView() {
        // 创建titleview
        let titleV = UIView(frame: CGRectMake(0, 0, 100, 44))
        navigationItem.titleView = titleV
        
        // 添加大文字label
        let largeLabel = UILabel(title: "发微博", color: UIColor.blackColor(), textFont: 16)
        titleV.addSubview(largeLabel)
        
        // 添加名字label
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.lightGrayColor(), textFont: 13)
        titleV.addSubview(nameLabel)
        
        // 设置约束
        largeLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleV.snp_top)
            make.centerX.equalTo(titleV.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(largeLabel.snp_bottom)
            make.bottom.equalTo(titleV.snp_bottom)
            make.centerX.equalTo(titleV.snp_centerX)
        }
    }
    
    // MARK: item的点击方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 发送请求
    @objc private func compose() {
        guard let token = UserAccountViewModel().access_token else {
            SVProgressHUD.showInfoWithStatus("请重新登录", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        var urlString = "2/statuses/update.json"
        
        var parameters = ["access_token" : token, "status" : myTextView.emoticonTextToStringText()]
        
        // 带图片的发布 https://upload.api.weibo.com/2/statuses/upload.json
        // 判断是否有配图
        if pictureVC.images.count > 0 {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            // 取出第一张图片
            let image = pictureVC.images.first
            let data = UIImagePNGRepresentation(image!)
            NetWorkingTool.shareNetworking.requestWith(data!, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
                self.finishedBlock(error)
            })
        }else {
            NetWorkingTool.shareNetworking.requestWith(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                self.finishedBlock(error)
            }
        }
    }
    
    private func finishedBlock(error: NSError?) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("发布失败,请检查网络", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        SVProgressHUD.showSuccessWithStatus("发布成功", maskType: SVProgressHUDMaskType.Gradient)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    // MARK: 懒加载
    private lazy var myTextView: UITextView = {
        let textV = UITextView(frame: CGRectMake(0, 0, screenBoundsWidth, textViewH))
//        textV.backgroundColor = UIColor.randomColor()
        textV.keyboardDismissMode = .OnDrag
        textV.alwaysBounceVertical = true
        textV.font = UIFont.systemFontOfSize(18)
        textV.delegate = self
        return textV
    }()
    
    // 占位label
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel(title: "分享新鲜事...", color: UIColor.lightGrayColor(), textFont: 18)
        return label
    }()
    
    // 键盘视图
    private lazy var emoticonKeyboard: XBEmoticonView = XBEmoticonView {[weak self] (emoticon) -> () in
        self?.myTextView.insertEmoticon(emoticon)
    }
    
    // toolbar
    private lazy var toolbar: ComposeToolbar = ComposeToolbar()
    
    // 配图集合视图
    private lazy var pictureVC: ComposePictureController = ComposePictureController()
}

// MARK:UITextViewDelegate
extension ComposeController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension ComposeController: ComposeToolbarDelegate {
    func composeToolbarClickPictureButton() {
        // 退出键盘,显示集合视图
        myTextView.resignFirstResponder()
        // 修改集合视图的约束
        pictureVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(400)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func composeToolbarClickEmoticonButton() {
        // 切换键盘
        print(__FUNCTION__)
        myTextView.resignFirstResponder()
        self.myTextView.inputView = self.myTextView.inputView == nil ? self.emoticonKeyboard : nil
        self.myTextView.becomeFirstResponder()
    }
}
